package com.loongtech.bi.action.system;

import com.loongtech.bi.entity.system.EntitySysFunction;
import com.loongtech.bi.entity.system.EntitySysModel;
import com.loongtech.bi.manager.system.SysFunctionManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysModelManager;
import com.loongtech.bi.support.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模块管理
 *
 * @author xckuang
 * @date 2014-10-06
 */
@Controller("modelManagerAction")
@Scope("view")
public class ModelManagerAction implements Serializable {
	private static final long serialVersionUID = 1L;
	@Autowired
	private Session session;
	@Autowired
	private SysLogManager sysLogManager;
	@Autowired
	private SysModelManager sysModelManager;
	@Autowired
	private SysFunctionManager sysFunctionManager;
	private EntitySysModel model;
	private Map<Integer, EntitySysModel> modelMap;
	private List<EntitySysModel> modelList = new ArrayList<>();
	private static final String MsgTag = "模块管理";

	@Autowired
	public void init() {
		setModel(new EntitySysModel());
		modelMap = new HashMap<>();
		EntitySysModel all = new EntitySysModel();
		all.setId(0);
		all.setDescription("根目录");
		modelMap.put(all.getId(), all);
		for(EntitySysModel domain : sysModelManager.findAll()) {
			modelMap.put(domain.getId(), domain);
		}
	}

    public void add() {
        FacesContext context = FacesContext.getCurrentInstance();

        // 判断参数
        String name = model.getName();
        if(null == name || name.isEmpty()) {
            context.addMessage(null, new FacesMessage("增加模块失败", "模块名为空!"));
            return;
        }
        int fatherId = model.getFatherId();
        if(fatherId > 0 && null == sysModelManager.get(fatherId)) {
            context.addMessage(null, new FacesMessage("增加模块失败", "父模块为空!"));
            return;
        }
        // 判断用户name是否已经被注册
        if(null != sysModelManager.getBy("name", name)) {
            context.addMessage(null, new FacesMessage("增加模块失败", "模块名称已存在!"));
            return;
        }
        if(null != sysModelManager.getBy("id", model.getId())) {
            context.addMessage(null, new FacesMessage("增加模块失败", "id已存在!"));
            return;
        }
        // 注册模块
        try {
            sysModelManager.persist(model);
            context.addMessage(null, new FacesMessage("增加模块成功", "模块名称为" + name));
            sysLogManager.addLog(session.getUserName(), "增加模块成功" + name);
            setModel(new EntitySysModel());
        } catch(Exception ex) {
            context.addMessage(null, new FacesMessage("增加模块失败", "注册时发生异常!"));
        }
    }

    public String getFatherName(int modelId) {
        EntitySysModel model = modelMap.get(modelId);
        return null != model ? model.getDescription() : "根目录";
    }

    private boolean empty(String param) {
		return null == param || param.trim().isEmpty();
	}

	public void search() {
		List<Object> params = new ArrayList<>();
		if(model.getId() != null && model.getId() > 0) {
			params.add("id");
			params.add(model.getId());
		}
		if(model.getSort() > 0) {
			params.add("sort");
			params.add(model.getSort());
		}
		if(model.getFatherId() > 0) {
			params.add("fatherId");
			params.add(model.getFatherId());
		}
		if(!empty(model.getName())) {
			params.add("name");
			params.add(model.getName());
		}
		if(!empty(model.getDescription())) {
			params.add("description");
			params.add(model.getDescription());
		}
		modelList.clear();
		if(params.isEmpty()) {
			modelList.addAll(sysModelManager.findAll());
		} else {
			modelList.addAll(sysModelManager.findBy(params.toArray(new Object[params.size()])));
		}
		sysLogManager.addLog(session.getUserName(), "模块查询成功!");
	}

	public void modify(EntitySysModel model) {
		FacesContext context = FacesContext.getCurrentInstance();
		EntitySysModel cur = sysModelManager.get(model.getId());
		if(cur != null) {
			sysModelManager.merge(model);
			sysLogManager.addLog(session.getUserName(), "模块修改成功!modelId=" + model.getId());
			context.addMessage(MsgTag, new FacesMessage("模块修改成功", "modelId=" + model.getId()));
			search();
		} else {
			sysLogManager.addLog(session.getUserName(), "模块修改失败,不存在模块modelId=" + model.getId());
			context.addMessage(MsgTag, new FacesMessage("模块修改失败", "不存在模块modelId=" + model.getId()));
		}
	}

	public void delete(int modelId) {
		FacesContext context = FacesContext.getCurrentInstance();
		List<EntitySysFunction> list = sysFunctionManager.findAll(EntitySysFunction.K.modelId, modelId);
		List<EntitySysModel> listParent = sysModelManager.findAll("fatherId",modelId);
		if(null != list && !list.isEmpty() || null != listParent && !listParent.isEmpty()) {
			context.addMessage(MsgTag, new FacesMessage("模块删除失败", "模块下有子模块或页面!modelId="+modelId));
			return;
		}
		if(null != sysModelManager.get(modelId)) {
			sysModelManager.removeById(modelId);
			sysLogManager.addLog(session.getUserName(), "模块删除成功!modelId=" + modelId);
			context.addMessage(MsgTag, new FacesMessage("模块删除成功", "模块modelId=" + modelId));
			search();
		}
	}

	public EntitySysModel getModel() {
		return model;
	}

	public void setModel(EntitySysModel model) {
		this.model = model;
	}

	public List<EntitySysModel> getModelList() {
		return modelList;
	}

	public void setModelList(List<EntitySysModel> modelList) {
		this.modelList = modelList;
	}

	public Map<Integer, EntitySysModel> getModelMap() {
		return modelMap;
	}

	public void setModelMap(Map<Integer, EntitySysModel> modelMap) {
		this.modelMap = modelMap;
	}
}
